package com.example.springboot.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.example.springboot.common.enums.OrderStatusEnum;
import com.example.springboot.entity.*;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.OrdersMapper;
import com.example.springboot.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.utils.SessionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ikun
 * @since 2023-05-30
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Resource
    ICartService cartService;
    
    @Resource
    IAddressService addressService;
    
    @Resource
    IOrderDetailService orderDetailService;
    
    @Resource
    IGoodsService goodsService;
    
    @Transactional(rollbackFor = Exception.class)  // 异常发生后回滚不进行save操作
    @Override
    public void addOrder(Integer addressId, List<Cart> carts) {
        Address address = addressService.getById(addressId);
        if (address == null) {
            throw new ServiceException("未找到地址信息");
        }
        Orders orders = new Orders();
        orders.setAddressId(addressId);
        
        User user = SessionUtils.getUser();
        orders.setUserId(user.getId());
        orders.setTime(DateUtil.now());
        orders.setOrderNo(String.valueOf(UUID.fastUUID()));  // 生成唯一订单编号
        orders.setStatus(OrderStatusEnum.NO_PAY.getValue());
        save(orders);  // 保存订单信息
        
        BigDecimal total = BigDecimal.ZERO;
        for (Cart cart : carts) {
            Integer id = cart.getGoodsId();
            Goods goods = goodsService.getById(id);
            if (goods == null) {
                throw new ServiceException("该商品{}已下架", goods.getName());
            }
            BigDecimal price = goods.getPrice();
            total = total.add(price.multiply(BigDecimal.valueOf(cart.getNum())));
            
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            orderDetail.setNum(cart.getNum());
            orderDetail.setPrice(goods.getPrice());
            orderDetail.setGoodsId(id);
            orderDetailService.save(orderDetail);
            
            // 清空购物车
            cartService.removeById(cart.getId());
        }
        orders.setTotal(total);
        updateById(orders);
        
        
    }
}
